const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const User = require('../models/User')
const Collection = require('../models/Collection')
const History = require('../models/History')
const Publication = require('../models/Publication')
const Notification = require('../models/Notification')

// JWT密钥
const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key'

// 中间件：验证JWT令牌
const authenticateToken = (req, res, next) => {
  try {
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]
    
    if (!token) {
      return res.status(401).json({ 
        success: false,
        message: '未提供认证令牌' 
      })
    }
    
    jwt.verify(token, JWT_SECRET, (err, user) => {
      if (err) {
        return res.status(403).json({ 
          success: false,
          message: '令牌无效或已过期' 
        })
      }
      req.user = user
      next()
    })
  } catch (error) {
    console.error('认证中间件错误:', error)
    return res.status(500).json({ 
      success: false,
      message: '认证过程中发生错误' 
    })
  }
}

// 所有用户路由都需要认证
router.use(authenticateToken)

// 获取用户个人信息
router.get('/profile', async (req, res) => {
  try {
    const user = await User.findById(req.user.id)
      .select('-password -__v')
      .lean()
    
    if (!user) {
      return res.status(404).json({ 
        success: false,
        message: '用户不存在' 
      })
    }
    
    // 更新最后活跃时间 (使用findByIdAndUpdate以减少一次数据库操作)
    await User.findByIdAndUpdate(req.user.id, { lastActive: Date.now() })
    
    // 返回用户信息
    res.json({
      success: true,
      data: {
        id: user._id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        bio: user.bio,
        registerDate: user.registerDate,
        lastActive: user.lastActive,
        level: user.level,
        points: user.points,
        followingCount: user.followingCount,
        followerCount: user.followerCount,
        publicationCount: user.publicationCount
      }
    })
  } catch (error) {
    console.error('获取用户信息错误:', error)
    res.status(500).json({ 
      success: false,
      message: '服务器错误' 
    })
  }
})

// 更新用户个人信息
router.put('/profile', async (req, res) => {
  try {
    const { nickname, avatar, bio } = req.body
    
    // 查找用户
    const user = await User.findById(req.user.id)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    // 更新用户信息
    if (nickname) user.nickname = nickname
    if (avatar) user.avatar = avatar
    if (bio !== undefined) user.bio = bio
    
    await user.save()
    
    res.json({
      id: user._id,
      email: user.email,
      nickname: user.nickname,
      avatar: user.avatar,
      bio: user.bio
    })
  } catch (error) {
    console.error('更新用户信息错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 修改密码
router.put('/password', async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body
    
    // 验证请求数据
    if (!currentPassword || !newPassword) {
      return res.status(400).json({ message: '当前密码和新密码不能为空' })
    }
    
    // 查找用户
    const user = await User.findById(req.user.id)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    // 验证当前密码
    const isMatch = await user.comparePassword(currentPassword)
    if (!isMatch) {
      return res.status(401).json({ message: '当前密码不正确' })
    }
    
    // 更新密码
    user.password = newPassword
    await user.save()
    
    res.json({ message: '密码已更新' })
  } catch (error) {
    console.error('修改密码错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取用户设置
router.get('/settings', async (req, res) => {
  try {
    const user = await User.findById(req.user.id).select('settings')
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    res.json(user.settings)
  } catch (error) {
    console.error('获取用户设置错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新外观设置
router.put('/settings/appearance', async (req, res) => {
  try {
    const { darkTheme, primaryColor, fontSize, density } = req.body
    
    // 查找用户
    const user = await User.findById(req.user.id)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    // 更新设置
    if (darkTheme !== undefined) user.settings.appearance.darkTheme = darkTheme
    if (primaryColor) user.settings.appearance.primaryColor = primaryColor
    if (fontSize) user.settings.appearance.fontSize = fontSize
    if (density) user.settings.appearance.density = density
    
    await user.save()
    
    res.json(user.settings.appearance)
  } catch (error) {
    console.error('更新外观设置错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新内容偏好设置
router.put('/settings/content', async (req, res) => {
  try {
    const { categories, languages, displayMode } = req.body
    
    // 查找用户
    const user = await User.findById(req.user.id)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    // 更新设置
    if (categories) user.settings.content.categories = categories
    if (languages) user.settings.content.languages = languages
    if (displayMode) user.settings.content.displayMode = displayMode
    
    await user.save()
    
    res.json(user.settings.content)
  } catch (error) {
    console.error('更新内容偏好设置错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新隐私设置
router.put('/settings/privacy', async (req, res) => {
  try {
    const { profileVisibility, activityTracking, showOnlineStatus, allowContentSharing } = req.body
    
    // 查找用户
    const user = await User.findById(req.user.id)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    // 更新设置
    if (profileVisibility) user.settings.privacy.profileVisibility = profileVisibility
    if (activityTracking !== undefined) user.settings.privacy.activityTracking = activityTracking
    if (showOnlineStatus !== undefined) user.settings.privacy.showOnlineStatus = showOnlineStatus
    if (allowContentSharing !== undefined) user.settings.privacy.allowContentSharing = allowContentSharing
    
    await user.save()
    
    res.json(user.settings.privacy)
  } catch (error) {
    console.error('更新隐私设置错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新通知设置
router.put('/settings/notifications', async (req, res) => {
  try {
    const { enabled, types, methods, emailFrequency } = req.body
    
    // 查找用户
    const user = await User.findById(req.user.id)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    // 更新设置
    if (enabled !== undefined) user.settings.notifications.enabled = enabled
    if (types) user.settings.notifications.types = types
    if (methods) user.settings.notifications.methods = methods
    if (emailFrequency) user.settings.notifications.emailFrequency = emailFrequency
    
    await user.save()
    
    res.json(user.settings.notifications)
  } catch (error) {
    console.error('更新通知设置错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取收藏内容
router.get('/collections', async (req, res) => {
  try {
    const { limit = 10, page = 1 } = req.query
    
    // 分页查询
    const collections = await Collection.find({ user: req.user.id })
      .sort({ collectedAt: -1 })
      .limit(Number(limit))
      .skip((Number(page) - 1) * Number(limit))
    
    res.json(collections)
  } catch (error) {
    console.error('获取收藏内容错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 添加收藏
router.post('/collections', async (req, res) => {
  try {
    const { contentId, contentType, title, thumbnail, tags, note } = req.body
    
    // 验证请求数据
    if (!contentId || !contentType || !title) {
      return res.status(400).json({ message: '内容ID、类型和标题不能为空' })
    }
    
    // 检查是否已收藏
    const existingCollection = await Collection.findOne({
      user: req.user.id,
      contentId
    })
    
    if (existingCollection) {
      return res.status(400).json({ message: '已经收藏过该内容' })
    }
    
    // 创建新收藏
    const newCollection = new Collection({
      user: req.user.id,
      contentId,
      contentType,
      title,
      thumbnail,
      tags,
      note
    })
    
    await newCollection.save()
    
    res.status(201).json(newCollection)
  } catch (error) {
    console.error('添加收藏错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 删除收藏
router.delete('/collections/:id', async (req, res) => {
  try {
    const collection = await Collection.findOne({
      _id: req.params.id,
      user: req.user.id
    })
    
    if (!collection) {
      return res.status(404).json({ message: '收藏不存在或无权限删除' })
    }
    
    await collection.remove()
    
    res.json({ message: '收藏已删除' })
  } catch (error) {
    console.error('删除收藏错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取浏览历史
router.get('/history', async (req, res) => {
  try {
    const { limit = 10, page = 1 } = req.query
    
    // 分页查询
    const history = await History.find({ user: req.user.id })
      .sort({ viewedAt: -1 })
      .limit(Number(limit))
      .skip((Number(page) - 1) * Number(limit))
    
    res.json(history)
  } catch (error) {
    console.error('获取浏览历史错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 添加浏览记录
router.post('/history', async (req, res) => {
  try {
    const { contentId, contentType, title, thumbnail, duration } = req.body
    
    // 验证请求数据
    if (!contentId || !contentType || !title) {
      return res.status(400).json({ message: '内容ID、类型和标题不能为空' })
    }
    
    // 检查是否已有该内容的浏览记录
    let historyItem = await History.findOne({
      user: req.user.id,
      contentId
    })
    
    if (historyItem) {
      // 更新现有记录
      historyItem.viewedAt = Date.now()
      historyItem.duration = duration || historyItem.duration
      await historyItem.save()
    } else {
      // 创建新记录
      historyItem = new History({
        user: req.user.id,
        contentId,
        contentType,
        title,
        thumbnail,
        duration: duration || 0
      })
      await historyItem.save()
    }
    
    res.status(201).json(historyItem)
  } catch (error) {
    console.error('添加浏览记录错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 清空浏览历史
router.delete('/history', async (req, res) => {
  try {
    await History.deleteMany({ user: req.user.id })
    res.json({ message: '浏览历史已清空' })
  } catch (error) {
    console.error('清空浏览历史错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取发布内容
router.get('/publications', async (req, res) => {
  try {
    const { limit = 10, page = 1, status } = req.query
    
    // 构建查询条件
    const query = { user: req.user.id }
    if (status) query.status = status
    
    // 分页查询
    const publications = await Publication.find(query)
      .sort({ publishedAt: -1 })
      .limit(Number(limit))
      .skip((Number(page) - 1) * Number(limit))
    
    res.json(publications)
  } catch (error) {
    console.error('获取发布内容错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 添加发布内容
router.post('/publications', async (req, res) => {
  try {
    const { title, contentType, content, thumbnail, tags, status, visibility } = req.body
    
    // 验证请求数据
    if (!title || !contentType || !content) {
      return res.status(400).json({ message: '标题、内容类型和正文不能为空' })
    }
    
    // 创建新发布内容
    const newPublication = new Publication({
      user: req.user.id,
      title,
      contentType,
      content,
      thumbnail,
      tags,
      status: status || 'published',
      visibility: visibility || 'public'
    })
    
    await newPublication.save()
    
    // 更新用户发布内容数量
    if (status !== 'draft') {
      await User.findByIdAndUpdate(req.user.id, { $inc: { publicationCount: 1 } })
    }
    
    res.status(201).json(newPublication)
  } catch (error) {
    console.error('添加发布内容错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新发布内容
router.put('/publications/:id', async (req, res) => {
  try {
    const { title, content, thumbnail, tags, status, visibility } = req.body
    
    // 查找发布内容
    const publication = await Publication.findOne({
      _id: req.params.id,
      user: req.user.id
    })
    
    if (!publication) {
      return res.status(404).json({ message: '内容不存在或无权限修改' })
    }
    
    // 检查是否从草稿变为发布状态
    const isDraftToPublished = publication.status === 'draft' && status === 'published'
    
    // 更新内容
    if (title) publication.title = title
    if (content) publication.content = content
    if (thumbnail) publication.thumbnail = thumbnail
    if (tags) publication.tags = tags
    if (status) publication.status = status
    if (visibility) publication.visibility = visibility
    
    // 如果从草稿变为发布状态，更新发布时间
    if (isDraftToPublished) {
      publication.publishedAt = Date.now()
    }
    
    await publication.save()
    
    // 如果从草稿变为发布状态，更新用户发布内容数量
    if (isDraftToPublished) {
      await User.findByIdAndUpdate(req.user.id, { $inc: { publicationCount: 1 } })
    }
    
    res.json(publication)
  } catch (error) {
    console.error('更新发布内容错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 删除发布内容
router.delete('/publications/:id', async (req, res) => {
  try {
    // 查找发布内容
    const publication = await Publication.findOne({
      _id: req.params.id,
      user: req.user.id
    })
    
    if (!publication) {
      return res.status(404).json({ message: '内容不存在或无权限删除' })
    }
    
    // 如果是已发布状态，需要减少用户发布内容数量
    const isPublished = publication.status === 'published'
    
    await publication.remove()
    
    // 更新用户发布内容数量
    if (isPublished) {
      await User.findByIdAndUpdate(req.user.id, { $inc: { publicationCount: -1 } })
    }
    
    res.json({ message: '内容已删除' })
  } catch (error) {
    console.error('删除发布内容错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取通知
router.get('/notifications', async (req, res) => {
  try {
    const notifications = await Notification.find({ user: req.user.id })
      .sort({ createdAt: -1 })
      .populate('sender', 'nickname avatar')
    
    res.json(notifications)
  } catch (error) {
    console.error('获取通知错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 标记通知为已读
router.put('/notifications/:id/read', async (req, res) => {
  try {
    const notification = await Notification.findOne({
      _id: req.params.id,
      user: req.user.id
    })
    
    if (!notification) {
      return res.status(404).json({ message: '通知不存在' })
    }
    
    notification.read = true
    await notification.save()
    
    res.json({ message: '通知已标记为已读' })
  } catch (error) {
    console.error('标记通知为已读错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 标记所有通知为已读
router.put('/notifications/read-all', async (req, res) => {
  try {
    await Notification.updateMany(
      { user: req.user.id, read: false },
      { $set: { read: true } }
    )
    
    res.json({ message: '所有通知已标记为已读' })
  } catch (error) {
    console.error('标记所有通知为已读错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 删除通知
router.delete('/notifications/:id', async (req, res) => {
  try {
    const notification = await Notification.findOne({
      _id: req.params.id,
      user: req.user.id
    })
    
    if (!notification) {
      return res.status(404).json({ message: '通知不存在' })
    }
    
    await notification.remove()
    
    res.json({ message: '通知已删除' })
  } catch (error) {
    console.error('删除通知错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 导出个人数据
router.get('/data/export', async (req, res) => {
  try {
    // 获取用户信息
    const user = await User.findById(req.user.id).select('-password')
    
    // 获取用户收藏
    const collections = await Collection.find({ user: req.user.id })
    
    // 获取用户浏览历史
    const history = await History.find({ user: req.user.id })
    
    // 获取用户发布内容
    const publications = await Publication.find({ user: req.user.id })
    
    // 组装数据
    const userData = {
      profile: user,
      collections,
      history,
      publications
    }
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/json')
    res.setHeader('Content-Disposition', 'attachment; filename=personal_data.json')
    
    // 发送数据
    res.json(userData)
  } catch (error) {
    console.error('导出个人数据错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 删除账户
router.delete('/account', async (req, res) => {
  try {
    // 删除用户相关数据
    await Collection.deleteMany({ user: req.user.id })
    await History.deleteMany({ user: req.user.id })
    await Publication.deleteMany({ user: req.user.id })
    await Notification.deleteMany({ user: req.user.id })
    
    // 删除用户账户
    await User.findByIdAndDelete(req.user.id)
    
    res.json({ message: '账户已删除' })
  } catch (error) {
    console.error('删除账户错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

module.exports = router